package lesson2;

import lesson3.MessageCreator;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.UUID;

/**
 * UDP 提供者,用户提供服务
 *
 * @author liliang
 * @date 2019/10/23.
 */
public class UdpProvider {

    public static void main(String[] args) throws IOException {
       String sn = UUID.randomUUID().toString();
       Provider provider = new Provider(sn);
       provider.start();

       System.in.read();
       provider.exit();
    }

    private static class Provider extends Thread {

        private final String sn;
        private boolean done = false;
        private DatagramSocket ds = null;

        public Provider(String sn) {
            super();
            this.sn = sn;
        }

        @Override
        public void run() {
            super.run();
            System.out.println("UDPProvider Started.");

            try {
                // 作为接收者,指定一个端口用于接收数据
                ds = new DatagramSocket(20000);

                while (!done) {


                    // 构建接收实体
                    byte[] buf = new byte[512];
                    DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);

                    // 接收
                    ds.receive(receivePacket);


                    // 打印接收到的信息与发送者的信息
                    // 发送者的 IP 地址
                    String ip = receivePacket.getAddress().getHostAddress();
                    int port = receivePacket.getPort();
                    int dataLen = receivePacket.getLength();
                    String data = new String(receivePacket.getData(), 0, dataLen);
                    System.out.println("UDPProvider receive form ip:" + ip + ",port:" + port + ",data:" + data);

                    int responsePort = MessageCreator.parsePort(data);
                    if (responsePort != -1) {

                        // 构建一分回送数据
                        String responseData = MessageCreator.buildSn(sn);
                        byte[] responseDataBytes = responseData.getBytes();
                        DatagramPacket responsePacket = new DatagramPacket(responseDataBytes,
                                responseDataBytes.length,
                                receivePacket.getAddress(),
                                responsePort);
                        ds.send(responsePacket);
                    }

                }
            } catch (Exception ignored) {
            } finally {
                close();
            }


            // 完成
            System.out.println("UDPProvider Finished.");
        }

        private void close() {
            if (ds != null) {
                ds.close();
                ds = null;
            }
        }

        void exit() {
            done = true;
            close();
        }
    }
}
